package com.hly.tool.ftp;

import org.apache.commons.net.ftp.FTPClient;

import java.io.*;

/**
 * @author ：Jack Hao
 * @date ：Created in 2021/7/30 10:14
 * @description：
 */
public class FTPUtil
{

    /**
     * 上传
     *
     * @param hostname    ip或域名地址
     * @param port        端口
     * @param username    用户名
     * @param password    密码
     * @param workingPath 服务器的工作目
     * @param file        要上传的文件
     * @param saveName    设置上传之后的文件名
     * @return
     */
    public static boolean upload(String hostname, int port, String username, String password, String workingPath, File file, String saveName) throws FileNotFoundException
    {
        InputStream inputStream = new FileInputStream(file);


        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //1 测试连接
        if (connect(ftpClient, hostname, port, username, password))
        {
            try
            {
                //2 检查工作目录是否存在 如果不存在就新建
                if (!ftpClient.changeWorkingDirectory(workingPath))
                {
                    ftpClient.makeDirectory(workingPath);
                }

                //2 检查工作目录是否存在
                if (ftpClient.changeWorkingDirectory(workingPath))
                {
                    // 3 检查是否上传成功
                    if (storeFile(ftpClient, saveName, inputStream))
                    {
                        flag = true;
                        disconnect(ftpClient);
                    }
                }
            } catch (IOException e)
            {
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }

        if (inputStream != null)
        {
            try
            {
                inputStream.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient)
    {
        if (ftpClient.isConnected())
        {
            try
            {
                ftpClient.disconnect();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password)
    {
        boolean flag = false;
        try
        {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            boolean login = ftpClient.login(username, password);
            if (login)
            {
                flag = true;
            } else
            {
                try
                {
                    disconnect(ftpClient);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        全路径。如/home/public/a.txt
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream)
    {
        boolean flag = false;
        try
        {
            if (ftpClient.storeFile(new String(saveName.getBytes("GBK"), "iso-8859-1"), fileInputStream))
            {
                flag = true;
                disconnect(ftpClient);
            }
        } catch (IOException e)
        {
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }


    public static void main(String[] args) throws FileNotFoundException
    {
        String hostname = "192.168.71.1";
        int port = 21;
        String username = "KY08";
        String password = "ky";
        String workingPath = "/userBehavior/";
        String str = "C:\\Users\\KY08\\Desktop\\测试.txt";
        File file = new File(str);
//        System.out.println(file.exists());
        String saveName = "测试.txt";
        boolean upload = upload(hostname, port, username, password, workingPath, file, saveName);
//        String s = System.getProperty("user.home") + File.separator;
//        System.out.println("s = "+s);
//        System.out.println(upload);

    }
}
